package com.xhb.ui.tools;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.xml.bind.DatatypeConverter;

import com.teamdev.jxbrowser.deps.com.google.common.collect.Lists;
import com.xhb.ui.http.HttpServer;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;

public class PicUtil {



    /**
     * 待合并的两张张图必须满足这样的前提，如果水平方向合并，则高度必须相等；如果是垂直方向合并，宽度必须相等。
     *
     * @param img1 待合并的第一张图
     * @param img2 带合并的第二张图
     * @return 返回合并后的BufferedImage对象
     */
    public static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2) {
        int w1 = img1.getWidth();
        int h1 = img1.getHeight();
        // 生成新图片
        BufferedImage destImage = new BufferedImage(w1 , h1, BufferedImage.TYPE_INT_RGB);
        Graphics2D   graphics2D = destImage.createGraphics();
        
        //写入背景图
        graphics2D.drawImage(img1, 0, 0, w1, h1, null);
        
        //写入人像图
        graphics2D.drawImage(img2, 0 , 0, w1, h1, null);
        
        graphics2D.dispose();
        return destImage;
    }

    /**
     * 生成新图片到本地
     */
    public static void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "PNG", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    
    
	public static void convertBase64ToImage(String base64Code, String filePath) {
		BufferedImage image;
		byte[] imageByte;
		try {
			imageByte = DatatypeConverter.parseBase64Binary(base64Code);
			ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
			image = ImageIO.read(new ByteArrayInputStream(imageByte));
			bis.close();
			File outputFile = new File(HttpServer.BASE_PATH + filePath);
			ImageIO.write(image, "png", outputFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	 public static String convertToBase64(String imagePath) {
	        String base64Image = "";
	        try {
	            Path path = Paths.get(imagePath);
	            byte[] imageBytes = Files.readAllBytes(path);
	            base64Image = Base64.getEncoder().encodeToString(imageBytes);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return base64Image;
	    }

	 
		public static void createImg(String path, String random) {
			java.util.List<File> popleFiles = Lists.newArrayList();
			String userName = path;
			File file1 = new File(userName + "\\1.png");
			if (file1.exists()) {
				popleFiles.add(file1);
			}
			File file2 = new File(userName + "\\2.png");
			if (file1.exists()) {
				popleFiles.add(file2);
			}
			File file3 = new File(userName + "\\3.png");
			if (file3.exists()) {
				popleFiles.add(file3);
			}
			if (popleFiles.isEmpty()) {
				JOptionPane.showMessageDialog(null, "人像图片最少一张 命名 1.png，2.png以此类推");
				return;
			}

			File beiDir = new File("C:\\zgymw\\背景图");
			File[] beiFiles = beiDir.listFiles();
			Integer c = 1;
			for (File file : popleFiles) {
				for (int J = 0; J < 42; J++) {
					try {
						Integer randomIndex = RandomUtil.randomInt(beiFiles.length);
						File beiFile = beiFiles[randomIndex];
						beiFiles = ArrayUtil.remove(beiFiles, randomIndex);

						BufferedImage mergeImg = PicUtil.mergeImage(ImageIO.read(beiFile), ImageIO.read(file));

						File fileDir = new File(userName + "\\n");
						if (!fileDir.exists()) {
							fileDir.mkdir();
						}
						if (userName.contains("江西") && fileDir.listFiles().length >= 12) {
							break;
						}
						if (fileDir.listFiles().length >= 42) {
							break;
						}

						Position position = new Position() {
							@Override
							public Point calculate(int enclosingWidth, int enclosingHeight, int width, int height,
									int insetLeft, int insetRight, int insetTop, int insetBottom) {
								if (random.equals("0")) {
									int x = (enclosingWidth / 2) - (width / 2) - RandomUtil.randomInt(10, 40);
									int y = enclosingHeight - height - insetBottom - RandomUtil.randomInt(100, 400);
									return new Point(x, y);
								} else {
									int x = (enclosingWidth / 2) - (width / 2) + RandomUtil.randomInt(10, 40);
									int y = enclosingHeight - height - insetBottom + RandomUtil.randomInt(100, 600);
									return new Point(x, y);
								}
							}
						};

						double scale = 0.6;

						int w = (int) (mergeImg.getWidth() * scale);
						int h = (int) (mergeImg.getHeight() * scale);

						File fileE = new File(userName + "\\n\\new" + c + ".png");

						if (!fileE.exists()) {
							Thumbnails.of(mergeImg).sourceRegion(position, w, h).size(w, h).keepAspectRatio(true)
									.toFile(fileE.getPath());
						}

					} catch (IOException e1) {
						e1.printStackTrace();
					}
					if (popleFiles.size() == 1) {
						if (J >= 32) {
							break;
						}
					}
					if (popleFiles.size() == 2) {
						if (userName.contains("江西")) {
							if (J >= 6) {
								J = 0;
								break;
							}
						} else {
							if (J >= 12) {
								J = 0;
								break;
							}
						}
					}
					if (popleFiles.size() == 3) {
						if (userName.contains("江西")) {
							if (J >= 4) {
								J = 0;
								break;
							}
						} else {
							if (J >= 14) {
								J = 0;
								break;
							}
						}
					}
					c++;
				}
			}
		}

    public static void main(String[] args) throws Exception {
//        InputStream is1 = new FileInputStream("C:\\zgymw\\背景图\\3672446f7e7f59e8afc8b739e3d2375.jpg");
//        InputStream is2 = new FileInputStream("C:\\zgymw\\浙江学员名单\\庄千军-市政工程施工员-330326198310140758\\1.png");
//        BufferedImage readImg1 = ImageIO.read(is1);
//        BufferedImage readImg2 = ImageIO.read(is2);
//        // 图像压缩  保证每张图片大小一致
////        int width = readImg1.getWidth();
////        int height = readImg1.getHeight();
////        readImg2 = resize(readImg2, width, height);
//        BufferedImage mergeImg = mergeImage(readImg1, readImg2);
//        writeImageLocal("C:\\zgymw\\浙江学员名单\\庄千军-市政工程施工员-330326198310140758\\n\\new.jpg", mergeImg);
        

    	BufferedImage img=ImageIO.read(new File("C:\\zgymw\\浙江学员名单\\庄千军-市政工程施工员-330326198310140758\\new4.png"));
    	
    	int w=(int)(img.getWidth() * 0.6);
    	int h=(int)(img.getHeight() * 0.6);
    	
     	
    	Position position=new Position() {
			@Override
			public Point calculate(int enclosingWidth, int enclosingHeight, int width, int height, int insetLeft,
					int insetRight, int insetTop, int insetBottom) {
				int x = (enclosingWidth / 2) - (width / 2);
				int y = enclosingHeight - height - insetBottom - 300;
				return new Point(x, y);
			}
		};
    	
		Thumbnails.of(img)
		.sourceRegion(position,w,h)
		.size(w,h)  
	    .keepAspectRatio(false)  
	    .toFile("C:\\zgymw\\浙江学员名单\\庄千军-市政工程施工员-330326198310140758\\aaa.png");
    }
}
